package com.cssl.service.impl;


import com.cssl.domain.DtsAccountTrace;
import com.cssl.domain.DtsUser;
import com.cssl.domain.DtsUserAccount;
import com.cssl.domain.dto.UserAccountDto;
import com.cssl.domain.dto.UserAccountTraceDto;
import com.cssl.mapper.DtsUserAccountMapper;
import com.cssl.service.DtsAccountTraceService;
import com.cssl.mapper.DtsAccountTraceMapper;
import com.cssl.util.InfoCode;
import com.cssl.util.RedisUtil;
import com.cssl.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 黄鑫
 * @description 针对表【dts_account_trace(账户流水表)】的数据库操作Service实现
 * @createDate 2024-07-29 15:49:04
 */
@Service
public class DtsAccountTraceServiceImpl
        implements DtsAccountTraceService {
    @Autowired
    private DtsAccountTraceMapper dtsAccountTraceMapper;
    @Autowired
    private DtsUserAccountMapper dtsUserAccount;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Map getAccountTraceList(UserAccountDto accountDto) {

        // Redis Key 存储，包含页码和条件
        StringBuilder redisKeyBuilder = new StringBuilder("AccountTraceList");

        // 检查昵称
        if (accountDto.getNickname() != null && !accountDto.getNickname().isEmpty()) {
            redisKeyBuilder.append(":nickname:").append(accountDto.getNickname());
        }

        // 检查手机号
        if (accountDto.getMobile() != null && !accountDto.getMobile().isEmpty()) {
            redisKeyBuilder.append(":mobile:").append(accountDto.getMobile());
        }
        if (accountDto.getStatusArray() != null && !accountDto.getStatusArray().isEmpty() && accountDto.getStatusArray().size() > 0) {
            redisKeyBuilder.append(":statusMap:");
            for (Integer sta:accountDto.getStatusArray()
                 ) {
                redisKeyBuilder.append(sta+",");
            }
        }
        redisKeyBuilder.append(":page:").append(accountDto.getPageNum());
        String redisKey = redisKeyBuilder.toString();
        System.out.println("redisKey:"+redisKey);
        List<DtsAccountTrace> accountTraces= null;

        // 检查 Redis 中是否存在当前页的数据
        if (redisUtil.hasKey(redisKey)) {
            System.out.println("从 Redis 中获取数据");
            accountTraces = (List<DtsAccountTrace>) redisUtil.get(redisKey);
            Map<String, Object> map1 = new HashMap<>();
            // 获取存储的总数

            map1.put("list", accountTraces);
            map1.put("total", redisUtil.get("AccountTraceList:total")); // 使用从 Redis 获取的总数
            map1.put("pageNum", accountDto.getPageNum());
            map1.put("pageSize", accountDto.getPageSize());
            return map1;
        } else {
            // 开始分页
            Page page = PageHelper.startPage(accountDto.getPageNum(), accountDto.getPageSize());
            System.out.println("从数据库中查询数据");
            accountTraces = dtsAccountTraceMapper.getAccountTraceList(accountDto);
            Map<String, Object> map = new HashMap<>();
            // 计算总数
//            long total = page.getTotal();

            // 将查询结果放入 Redis，设置过期时间，例如：1小时
            redisUtil.set(redisKey, accountTraces, 3600);
            redisUtil.set("AccountTraceList:total", dtsAccountTraceMapper.getAccountCount(), 3600);

            map.put("list", page.getResult());
            map.put("total", page.getTotal()); // 使用从数据库计算的总数
            map.put("totalPage", page.getPages());
            map.put("pageNum", page.getPageNum());
            map.put("pageSize", page.getPageSize());
            return map;
        }



    }

    @Override
    public Result approveAccountTrace(UserAccountTraceDto userAccountTraceDto) {
        //根据id查询流水表
        DtsAccountTrace accountTraceByid = dtsAccountTraceMapper.getAccountTraceByid(userAccountTraceDto.getId());

        //1代表前端同意审批
        if (userAccountTraceDto.getStatus() == 1) {
            //根据id查询审批表
            DtsUserAccount userAccountByid = dtsUserAccount.getUserAccountByid(accountTraceByid.getUserId());
            if (userAccountByid != null) {
                //修改审批表总金额
                userAccountByid.setRemainAmount(userAccountByid.getRemainAmount().subtract(accountTraceByid.getAmount()));
                userAccountByid.setTotalAmount(userAccountByid.getTotalAmount().subtract(accountTraceByid.getAmount()));
                if (dtsUserAccount.UpdReainAmount(userAccountByid) == 0) {
                    return Result.result(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, null, System.currentTimeMillis());
                }
            }
            // 首先检查是否有任何以 "DtsAdList:" 开头的键
            Set<String> keys = redisUtil.keys("AccountTraceList:*");
            if (!keys.isEmpty()) {
                // 删除所有匹配的键
                for (String key : keys) {
                    redisUtil.del(key);
                }
            }
            dtsAccountTraceMapper.updateAccountTraceStatus(userAccountTraceDto.getId());
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, null, System.currentTimeMillis());
        } else {

            return Result.result(InfoCode.NOT_FOUND, InfoCode.MESSAGE_NOT_FOUND, null, System.currentTimeMillis());
        }


    }



}




